const lark = require("@larksuiteoapi/node-sdk");
const fs = require('fs');
const path = require('path');

// 读取.env文件
function loadEnvConfig() {
  try {
    const envPath = path.join(__dirname, '../.env');
    const envContent = fs.readFileSync(envPath, 'utf8');
    const envVars = {};
    
    envContent.split('\n').forEach(line => {
      const trimmedLine = line.trim();
      if (trimmedLine && !trimmedLine.startsWith('#')) {
        const [key, ...valueParts] = trimmedLine.split('=');
        if (key && valueParts.length > 0) {
          envVars[key.trim()] = valueParts.join('=').trim();
        }
      }
    });
    
    return envVars;
  } catch (error) {
    console.error('读取.env文件失败:', error.message);
    return {};
  }
}

const envVars = loadEnvConfig();

const client = new lark.Client({
  appId: envVars.FEISHU_APP_ID || "cli_a85b801777ad500b",
  appSecret: envVars.FEISHU_APP_SECRET || "IWokuQK0qh0wMixQ8wFUMbBOd2LsY16n",
  appType: lark.AppType.SelfBuild,
  domain: lark.Domain.Feishu,
});

// 设置用户访问令牌（如果配置了的话）
if (envVars.FEISHU_USER_ACCESS_TOKEN) {
  client.userAccessToken = envVars.FEISHU_USER_ACCESS_TOKEN;
}

module.exports = client;